#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node
{
    int data;
    struct node *next;
} node;

// 创建一个空链表
node *list_Create()
{
    node *head;
    head = (node *)malloc(sizeof(node));
    // 判断是否分配成功
    if (head == NULL)
    {
        printf("malloc failed\n");
    }
    // 头结点不用来存储数据
    head->data = 0;
    head->next = NULL;
    return head;
}

// 尾插  失败：-1
int list_tail_insert(node *H, int value)
{
    // 链表是否存在
    if (H == NULL)
    {
        printf("list is error\n"); // 链表不存在
        return -1;
    }
    // 创建一个新结点
    node *newnode = (node *)malloc(sizeof(node));
    if (newnode == NULL)
    {
        printf("newnode malloc faild\n"); // 新结点创建失败
        return -1;
    }
    // 将新数据给新结点
    newnode->data = value;
    newnode->next = NULL;

    // 找到尾结点
    node *p_head = H;
    while (p_head->next != NULL)
    {
        p_head = p_head->next;
    }
    // 此时p_head指向尾结点
    p_head->next = newnode;
    return 0;
}
int show_list(node *H)
{
    if (H == NULL)
    {
        printf("list is error\n");
        return -1;
    }
    if (H->next == NULL)
    {
        printf("list is null\n");
        return -1;
    }
    node *p = H->next;
    while (p != NULL)
    {
        printf("%d\t", p->data);
        p = p->next;
    }
    printf("\n");
    return 0;
}
int del_node(node *H, int newdata)
{
    if (H == NULL)
    {
        printf("list is error\n");
        return -1;
    }
    if (H->next == NULL)
    {
        printf("list is empty\n");
        return -1;
    }
    node *p, *q;
    p = H->next;//头结点的下一个
    q=H;//头结点
    while (p != NULL)
    {
        if (p->data != newdata)
        {
            q = p;
            p = p->next;
        }
        else
        {
            break;
        }
    }
    if(p==NULL)
    {
        printf("删除的结点为:%d\n",newdata);
        printf("not find newdata,del faild\n");
        return -1;
    }
    //此时q指向newdata的前一个结点
    //    p指向newdata结点
    printf("删除的结点为:%d\n",newdata);
    q->next = p->next;
    memset(p, 0, sizeof(node));
    free(p);
    return 0;
}
int main(int argc, char const *argv[])
{
    node *linklist = list_Create(linklist);
    list_tail_insert(linklist, 1);
    list_tail_insert(linklist, 2);
    list_tail_insert(linklist, 3);
    list_tail_insert(linklist, 4);
    list_tail_insert(linklist, 5);
    show_list(linklist);


    del_node(linklist, 0);
    show_list(linklist);
    del_node(linklist, 1);
    show_list(linklist);
    del_node(linklist, 5);
    show_list(linklist);
    del_node(linklist, 6);
    show_list(linklist);
    return 0;
}
